<template>
  <div class="codeFile">
    <el-form
      :rules="rulesRule"
      :model="formListOne"
      ref="FormListOne"
      id="FormListOne"
      label-width="100px"
    >
      <p>xlsx，file-saver生成表格</p>
      <p style="margin-bottom: 20px">xlsx获取xlsx文件中的数据</p>
      <el-form-item label="字典名" prop="name">
        <el-input
          v-model="formListOne.name"
          placeholder="请输入字典名"
        ></el-input>
      </el-form-item>
      <el-form-item label="字典类型" prop="type">
        <el-input
          v-model="formListOne.type"
          placeholder="请输入字典类型"
        ></el-input>
      </el-form-item>
      <el-form-item label="字典描述" prop="des">
        <el-input
          :rows="2"
          type="textarea"
          v-model="formListOne.des"
          placeholder="请输入字典描述"
        ></el-input>
      </el-form-item>

      <el-form-item label="对应规则" prop="datatype">
        <el-radio-group v-model="formListOne.datatype">
          <el-radio :label="1">value对应</el-radio>
          <el-radio :label="2">string对应</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="设置字典规则" prop="guize">
        <div class="rulesbox">
          <el-radio-group v-model="formListOne.guize" @change="guizeChange">
            <el-radio :label="1">本地文件上传</el-radio>
            <el-radio :label="2">手动输入</el-radio>
          </el-radio-group>
          <div
            v-if="formListOne.guize == 1"
            class="downloadMo"
            @click="downloadmuban"
          >
            下载模板 <Icon name="el-icon-QuestionFilled" />
          </div>
        </div>
      </el-form-item>
      <el-form-item v-if="formListOne.guize == 1" label="上传">
        <el-upload
          :show-file-list="false"
          class="upload-demo"
          :http-request="filerequest"
          drag
          action
        >
          <el-icon :size="20">
            <Download />
          </el-icon>
          <div class="el-upload__text">拖拽文件至此 或 <em>点击上传</em></div>
        </el-upload>
      </el-form-item>
    </el-form>

    <el-form
      id="FormListTwo"
      style="margin-left: 70px; margin-bottom: 30px"
      label-position="top"
      :model="formListOne"
      ref="FormList"
      label-width="100px"
    >
      <el-form-item
        class="item-list"
        v-for="(domain, index) in formListOne.domains"
        :key="domain.value"
      >
        <el-form-item
          :label="index == 0 ? 'value' : ''"
          :prop="'domains.' + index + '.value'"
          :rules="{
            required: true,
            message: '请填写完整',
            trigger: 'blur',
          }"
        >
          <el-input placeholder="请填写" v-model="domain.value"></el-input>
        </el-form-item>
        <el-form-item
          v-if="formListOne.datatype == 1"
          :label="index == 0 ? 'label' : ''"
          :prop="'domains.' + index + '.label'"
          :rules="{
            required: true,
            message: '请填写完整',
            trigger: 'blur',
          }"
        >
          <el-input placeholder="请填写" v-model="domain.label"></el-input>
        </el-form-item>
        <el-form-item :label="index == 0 ? `\u2028` : ''">
          <div
            v-if="formListOne.domains.length > 1"
            class="delete-icon"
            @click.prevent="removeDomain(index)"
          >
            <el-icon :size="20" color="#f56c6c">
              <Delete />
            </el-icon>
          </div>
          <!-- <el-button v-if="formListOne.domains.length > 1"  class="delete-icon" @click.prevent="removeDomain(index)">删除</el-button> -->
          <!-- <el-button v-if="index == formListOne.domains.length - 1" class="delete-icon" @click.prevent="addDomain">新增</el-button> -->
        </el-form-item>
      </el-form-item>
      <el-form-item>
        <el-button
          class="add-btn"
          type="primary"
          plain
          @click.prevent="addDomain"
          >新增</el-button
        >
      </el-form-item>
    </el-form>
    <el-button class="submit-btn" type="primary" @click="submitForm"
      >提交</el-button
    >
  </div>
  <div style="display: none">
    <el-table id="exportTab">
      <el-table-column label="value" width="160"></el-table-column>
      <el-table-column
        v-if="formListOne.datatype == 1"
        label="label"
        width="160"
      ></el-table-column>
    </el-table>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, nextTick, watch } from "vue";
import * as XLSX from "xlsx";
import FileSaver from "file-saver";

const emit = defineEmits(["handleCancle"]);

// const props = defineProps({
//   id: {
//       type: String,
//       default: '',
//   },
// })

const defaultdata = {
  name: "", //字典名
  type: "", //字典类型
  des: "", //字典描述
  guize: 2, //字典规则
  datatype: 1, //对应规则
  domains: [{ value: "", label: "" }],
};

const FormList = ref();
const FormListOne = ref();
const formListOne = ref(JSON.parse(JSON.stringify(defaultdata)));

const rulesRule = {
  name: [{ required: true, message: "请输入字典名", trigger: "change" }],
  type: [{ required: true, message: "请选择字典类型", trigger: "change" }],
};

//数据回显
// watch(props, () => {
//   if (props.id) {
//       getDetailDta(props.id)
//   }
// })

// const getDetailDta = (id) => {
//   formListOne.value = {
//       name: 'wewewew', //字典名
//       type: '111', //字典类型
//       des: '232324e23423423', //字典描述
//       guize: 2, //字典规则
//       datatype: 1, //对应规则
//       domains: [
//           { value: '2', label: '2' },
//           { value: '2', label: '2' },
//           { value: '2', label: '2' },
//       ],
//   }
// }

//移除字典项
const removeDomain = (index) => {
  let list = JSON.parse(JSON.stringify(formListOne.value.domains));
  list.splice(index, 1);
  formListOne.value.domains = list;
};

//改变文件上传方式
const guizeChange = (e) => {};

//下载模板
const downloadmuban = () => {
  let xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
  let table = document.querySelector("#exportTab").cloneNode(true);
  var wb = XLSX.utils.table_to_book(table, xlsxParam);
  var wbout = XLSX.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array",
  });
  try {
    FileSaver.saveAs(
      new Blob([wbout], { type: "application/octet-stream" }),
      "字段模板.xlsx"
    );
  } catch (e) {
    if (typeof console !== "undefined") {
      console.log(e, wbout);
    }
  }
  return wbout;
};

// //上传文件钩子
const filerequest = (e: any) => {
  let file = e.file;
  if (!file) return;
  let reader = new FileReader();
  reader.readAsBinaryString(file);
  reader.onload = (ev: any) => {
    let data = ev.target.result;
    let result = toJosn(data);
    console.log(result);
    formListOne.value.domains = result.results;
  };
};

//获取表格结果
const toJosn = (data: any) => {
  let workbook = XLSX.read(data, { type: "binary" });
  const firstSheetName = workbook.SheetNames[0];
  const worksheet = workbook.Sheets[firstSheetName];
  const header = get_header_row(worksheet); // 第一行头部的数据
  const results = XLSX.utils.sheet_to_json(worksheet); // 后面对应的每行数据
  return {
    header,
    results,
  };
};

//获取第一行头部数据
const get_header_row = (sheet) => {
  const headers = [];
  const range = XLSX.utils.decode_range(sheet["!ref"]);
  let C;
  const R = range.s.r; /* start in the first row */
  for (C = range.s.c; C <= range.e.c; ++C) {
    /* walk every column in the range */
    var cell =
      sheet[
        XLSX.utils.encode_cell({ c: C, r: R })
      ]; /* find the cell in the first row */
    var hdr = "UNKNOWN " + C; // <-- replace with your desired default
    if (cell && cell.t) hdr = XLSX.utils.format_cell(cell);
    headers.push(hdr);
  }
  return headers;
};

//提交
const submitForm = async () => {
  let passone = false;
  let passtwo = false;
  await FormListOne.value.validate((valid) => {
    if (valid) {
      passone = true;
    } else {
      console.log("error submit!!");
      return false;
    }
  });
  await FormList.value.validate((valid) => {
    if (valid) {
      passtwo = true;
    } else {
      console.log("error submit!!");
      return false;
    }
  });
  if (passone && passtwo) {
    console.log(formListOne.value);
    formListOne.value = JSON.parse(JSON.stringify(defaultdata));
  }
};

//新增
const addDomain = () => {
  let list = JSON.parse(JSON.stringify(formListOne.value.domains));
  list.push({
    value: "",
    label: "",
  });
  formListOne.value.domains = list;
};
</script>
<style lang="scss" scoped>
.codeFile {
  //     position: relative;
  //     height: 100%;
  .item-list {
    display: flex;
    position: relative;
    .el-form-item {
      margin-left: 20px;
    }
    .delete-icon {
      cursor: pointer;
      text-align: center;
      line-height: 1;
    }
  }
  .add-btn {
    width: 194px;
    margin-left: 20px;
  }
  .rulesbox {
    width: 100%;
    display: flex;
    justify-content: space-between;
    .downloadMo {
      color: #409eff;
      cursor: pointer;
      .icon {
        color: #ccc !important;
        cursor: pointer;
        font-size: 17px !important;
      }
    }
  }
  .submit-btn {
    margin-left: 50%;
  }
}
</style>
